package com.zijin.utils;


import org.springframework.lang.Nullable;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/** file工具
 * author xiaochi
 * date 2024/9/23
 * 提供了Base64，File，MultipartFile之间的互相转换
 */
public class ZiJinFileUtil {

    /**
     * MultipartFile对象转File
     * @param file
     * @return
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File convFile = new File(file.getOriginalFilename());
        if (convFile.createNewFile()){
            try (InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(convFile)) {
                int byteRead = 0;
                byte[] buffer = new byte[4096];
                while ((byteRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, byteRead);
                }
            }
        }
        return convFile;
    }

    /**
     * Base64格式图片转input输入流
     * @throws Exception
     */
    public static InputStream base64ToInputStream(String base64Str) throws Exception {
        byte[] bytes = base64ToByteArray(base64Str);
        return new ByteArrayInputStream(bytes);
    }

    /**
     * InputStream转Base64格式
     * @throws Exception
     */
    public static String toBase64(InputStream in) throws Exception {
        return toBase64(in,"jpg");
    }

    /**
     * Base64格式图片转byte[]数组
     * @throws Exception
     */
    public static byte[] base64ToByteArray(String base64Str) throws Exception {
        base64Str = base64Str.replaceAll("data:image/(jpg|png|jpeg);base64,","");
        return Base64.getDecoder().decode(base64Str);
    }

    /**
     * InputStream转Base64格式
     * @throws Exception
     */
    public static String toBase64(InputStream in,String imageType) throws Exception {
        byte[] bytes = new byte[4096];
        int len;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while ((len = in.read(bytes)) != -1){
            out.write(bytes,0,len);
        }
        out.flush();
        return "data:image/"+imageType+";base64,"+ new String(Base64.getEncoder().encode(out.toByteArray()), StandardCharsets.UTF_8);
    }

    /**
     * Base64格式图片转MultipartFile对象
     * 调用：FileUtil.base64ToMultipartFile("123.jpg", "123.jpg", "jpg", Base64格式图片字符串);
     * @throws Exception
     */
    public static MultipartFile base64ToMultipartFile(String fileName,String originalFilename,String contentType,String base64Str) throws Exception {
        byte[] bytes = base64ToByteArray(base64Str);
        return new DefaultMultiPartFile(fileName,originalFilename,contentType, bytes);
    }

    /**
     * File转MultipartFile对象
     * 调用：FileUtil.base64ToMultipartFile("123.jpg", "123.jpg", "jpg", 文件字节数组);
     * @throws Exception
     */
    public static MultipartFile fileToMultipartFile(String fileName,String originalFilename,String contentType,byte[] content) throws Exception {
        return new DefaultMultiPartFile(fileName,originalFilename,contentType, content);
    }

    /**
     * BufferedImage转Base64编码
     * 调用：FileUtil.toBase64(BufferedImage,"jpg");
     * @throws Exception
     */

    public static String bufferedImagetoBase64(BufferedImage image, String type) {
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            // 将BufferedImage写入ByteArrayOutputStream
            ImageIO.write(image, type, bos);
            // 将输出流转为字节数组
            byte[] imageBytes = bos.toByteArray();
            // 使用Base64编码字节数组
            imageString = Base64.getEncoder().encodeToString(imageBytes);
            // 关闭流
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return imageString;
    }

    public static class DefaultMultiPartFile implements MultipartFile {
        private final String name;
        private String originalFilename;
        @Nullable
        private String contentType;
        private final byte[] content;

        public DefaultMultiPartFile(String name, @Nullable byte[] content) {
            this(name, name, (String)null, content);
        }

        public DefaultMultiPartFile(String name, String originalFilename, @Nullable String contentType, byte[] content) {
            this.name = name;
            this.originalFilename = originalFilename;
            this.contentType = contentType;
            this.content = content;
        }

        @Override
        public String getName() {
            return this.name;
        }

        @Override
        public String getOriginalFilename() {
            return this.originalFilename;
        }

        @Override
        public String getContentType() {
            return this.contentType;
        }

        @Override
        public boolean isEmpty() {
            return content.length==0;
        }

        @Override
        public long getSize() {
            return content.length;
        }

        @Override
        public byte[] getBytes() throws IOException {
            return content;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(content);
        }

        @Override
        public void transferTo(File file) throws IOException, IllegalStateException {
            FileCopyUtils.copy(this.content, file);
        }
    }
}